
package com.kugou.game.sdk.utils;

import com.kugou.download.DownloadFile;
import com.kugou.download.FileDownloader;
import com.kugou.download.IProgressListener;
import com.kugou.download.manager.ParamsWrapper;
import com.kugou.framework.utils.SDCardUtil;
import com.kugou.game.sdk.core.FolderManager;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.download.DownloadOperator;
import com.kugou.game.sdk.download.DownloadServiceUtil;
import com.kugou.game.sdk.entity.AppInfo;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import java.util.Hashtable;
import java.util.List;

/**
 * 描述:下载辅助类
 * 
 * @author chenys
 * @since 2013-10-23 下午4:08:01
 */
public class DownloadHelper {

    /**
     * 通知进度变化
     */
    public final static int NOTIFY_PROGRESS_CHANGED = 1;

    /**
     * 通知下载出错
     */
    public final static int NOTIFY_DOWNLOAD_ERROR = 2;

    private static Hashtable<String, Boolean> sDownloadStateTable = new Hashtable<String, Boolean>();

    private DownloadHelper() {
    }

    /**
     * 初始化下载文件状态
     */
    public static void initDownloadState() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                List<DownloadFile> files = DownloadOperator.getInstance().query(null, null, null);
                if (files != null && files.size() > 0) {
                    for (DownloadFile file : files) {
                        sDownloadStateTable.put(file.getKey(),
                                file.getState() == FileDownloader.FINISH ? true : false);
                    }
                }
            }
        }).start();
    }

    /**
     * 设置文件是否下载完毕
     * 
     * @param key
     * @param isDownloadFinish
     */
    public static void updateDownloadState(String key, boolean isDownloadFinish) {
        sDownloadStateTable.put(key, isDownloadFinish);
    }

    /**
     * 下载广播intent
     * 
     * @param key
     * @param notifyType
     * @param state
     * @return
     */
    public static Intent createDownloadIntent(String key, int notifyType, int state) {
        Intent intent = new Intent(SDKActions.ACTION_DOWNLOAD_STATE_CHANGED);
        intent.putExtra("key", key);
        intent.putExtra("notifyType", notifyType);
        intent.putExtra("state", state);
        return intent;
    }

    /**
     * 开始下载
     * 
     * @param paramsWrapper
     * @param listener
     */
    public static void download(ParamsWrapper paramsWrapper, IProgressListener listener) {
        Context context = SDKControler.getContext();
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            ToastUtil.showMsg("请检查您的网络连接");
            return;
        }
        if (!SDCardUtil.hasSDCard()) {
            ToastUtil.showMsg("SD卡未挂载");
            return;
        }
        if (!SDCardUtil.hasEnoughSpace(paramsWrapper.getFileSize())) {
            ToastUtil.showMsg("SD卡空间不足");
            return;
        }
        DownloadServiceUtil.download(paramsWrapper, listener);
    }

    /**
     * 停止下载
     * 
     * @param key
     */
    public static void stopDownload(String key) {
        if (DownloadServiceUtil.isDownloading(key)) {
            DownloadServiceUtil.stopDownload(key);
        } else if (DownloadServiceUtil.isInWaittingQueue(key)) {
            DownloadServiceUtil.removeFromWaittingQueue(key);
        }
    }

    /**
     * 下载进度描述
     * 
     * @param file
     * @return
     */
    public static String getDownloadingIntro(DownloadFile file) {
        long haveRead = file.getHaveRead();
        long fileSize = file.getFileSize();
        int percent = (int) ((float) haveRead / fileSize * 100);
        percent = Math.min(Math.abs(percent), 100);
        int speed = file.getStatis().getCurrentSpeed();

        StringBuilder intro = new StringBuilder();
        intro.append(speed + "K/S");
        intro.append("     ");
        intro.append(StringUtil.getSizeStr(haveRead));
        intro.append("/");
        intro.append(StringUtil.getSizeStr(fileSize));
        intro.append("  ");

        // intro.append(percent + "%");

        return intro.toString();
    }

    /**
     * 根据要求显示：下载进度描述
     * 
     * @param file
     * @param beenDownloaded 是否显示当前下载量
     * @param currentSpeed 是否显示当前速度
     * @param currentPercent 是否显示当前百分比
     * @return
     */
    public static String getDownloadingIntroAsRequired(DownloadFile file, boolean beenDownloaded,
            boolean currentSpeed, boolean currentPercent) {
        long haveRead = file.getHaveRead();
        long fileSize = file.getFileSize();
        int percent = (int) ((float) haveRead / fileSize * 100);
        percent = Math.min(Math.abs(percent), 100);
        int speed = file.getStatis().getCurrentSpeed();

        StringBuilder intro = new StringBuilder();
        if (beenDownloaded) {
            intro.append(StringUtil.getSizeStr(haveRead));
            intro.append("/");
            intro.append(StringUtil.getSizeStr(fileSize));
        }
        if (currentSpeed && DownloadServiceUtil.isDownloading(file.getKey())) {
            intro.append("  ");
            intro.append(speed + "K/S");
        }
        if (currentPercent) {
            intro.append("  ");
            intro.append(percent + "%");
        }

        return intro.toString();
    }

    /**
     * 获取下载进度
     * 
     * @param file
     * @return
     */
    public static int getDownloadingProgress(DownloadFile file) {
        long haveRead = file.getHaveRead();
        long fileSize = file.getFileSize();
        if (fileSize > 0) {
            int percent = (int) ((float) haveRead / fileSize * 100);
            percent = Math.min(Math.abs(percent), 100);
            return percent;
        } else {
            return 0;
        }
    }

    /**
     * 获取等待下载描述
     * 
     * @param file
     * @return
     */
    public static String getWaittingIntro(DownloadFile file) {
        long haveRead = file.getHaveRead();
        long fileSize = file.getFileSize();
        int percent = (int) ((float) haveRead / fileSize * 100);
        percent = Math.min(Math.abs(percent), 100);

        StringBuilder intro = new StringBuilder();
        intro.append("连接中");
        intro.append("  ");
        intro.append(StringUtil.getSizeStr(haveRead));
        intro.append("/");
        intro.append(StringUtil.getSizeStr(fileSize));
        intro.append("  ");
        intro.append(percent + "%");

        return intro.toString();
    }

    /**
     * 获取停止下载描述
     * 
     * @param file
     * @return
     */
    public static String getPauseIntro(DownloadFile file) {
        long haveRead = file.getHaveRead();
        long fileSize = file.getFileSize();
        int percent = (int) ((float) haveRead / fileSize * 100);
        percent = Math.min(Math.abs(percent), 100);

        StringBuilder intro = new StringBuilder();
        intro.append(StringUtil.getSizeStr(haveRead));
        intro.append("/");
        intro.append(StringUtil.getSizeStr(fileSize));
        intro.append("  ");
        intro.append(percent + "%");

        return intro.toString();
    }

    /**
     * 生成APP下载保存路径
     * 
     * @param app
     * @return
     */
    public static String createAppSavePath(AppInfo app) {
        StringBuilder savePath = new StringBuilder();
        savePath.append(FolderManager.APK_FOLDER);
        savePath.append(formatFilePath(app.getAppName()));
        savePath.append("-");
        savePath.append(app.getPackageName());
        savePath.append(".apk");
        return savePath.toString();
    }

    /**
     * 生成APP文件名
     * 
     * @param app
     * @return
     */
    public static String createAppFileName(AppInfo app) {
        StringBuilder fileName = new StringBuilder();
        fileName.append(formatFilePath(app.getAppName()));
        fileName.append(".apk");
        return fileName.toString();
    }

    /**
     * 格式化文件路径（去除一些特殊字符）
     * 
     * @param filePath
     * @return
     */
    public static String formatFilePath(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        return filePath.replace("\\", "").replace("/", "").replace("*", "").replace("?", "")
                .replace(":", "").replace("\"", "").replace("<", "").replace(">", "")
                .replace("|", "");
    }

    /**
     * 生成下载参数类
     * 
     * @param app
     * @return
     */
    public static ParamsWrapper getParamsWrapperFromAppinfo(AppInfo app) {
        long appId = app.getAppId();
        String resUrl = app.getDownloadUrl();
        String key = app.getFilehash();

        String savePath = DownloadHelper.createAppSavePath(app);
        String fileName = DownloadHelper.createAppFileName(app);
        long fileSize = app.getFileSize();
        String iconUrl = app.getIconUrl();
        String packageName = app.getPackageName();
        String versionCode = String.valueOf(app.getVersionCode());
        String versionName = app.getVersionName();
        long gameId = app.getGameid();
        int downloadSourceId = app.getDownloadSourceId();
        int needAutoDownload = app.getNeedAutoDownload();
        long downloadCompleteTime = app.getDownloadCompleteTime();
        String statParams = app.getStatparams();

        ParamsWrapper pw = new ParamsWrapper();
        // 文件唯一标识符
        pw.setKey(key);
        // 下载地址
        pw.setResUrl(resUrl);
        // 文件保存路径
        pw.setFilePath(savePath);
        // 文件名,带扩展名
        pw.setFileName(fileName);
        // 文件大小
        pw.setFileSize(fileSize);
        // 文件分类
        pw.setClassId(FileType.TYPE_APP_FILE);
        // 应用图标下载地址
        pw.setExt1(iconUrl);
        // 包名
        pw.setExt2(packageName);
        // 版本号
        pw.setExt3(versionCode);
        // 版本名称
        pw.setExt4(versionName);
        // appId
        pw.setExt5(String.valueOf(appId));
        // gameid
        pw.setExt6(String.valueOf(gameId));
        // downloadsourceid
        pw.setExt7(String.valueOf(downloadSourceId));
        // downloadCompleteTime
        pw.setExt8(String.valueOf(downloadCompleteTime));
        // 是否需要自动下载
        pw.setExt9(String.valueOf(needAutoDownload));
        // 下载统计的扩展参数列表，用于服务端做标记
        pw.setExt10(statParams);
        return pw;
    }

    /**
     * 生成下载参数类
     * 
     * @param file
     * @return
     */
    public static ParamsWrapper getParamsWrapperFromDownloadFile(DownloadFile file) {
        String key = file.getKey();
        String resUrl = file.getResUrl();
        String savePath = file.getFilePath();
        String fileName = file.getFileName();
        long fileSize = file.getFileSize();
        int classId = file.getClassId();
        String iconUrl = file.getExt1();
        String packageName = file.getExt2();
        String versionCode = file.getExt3();
        String versionName = file.getExt4();
        String appId = file.getExt5();
        String gameid = file.getExt6();
        String downloadSourceId = file.getExt7();
        String downloadCompleteTime = file.getExt8();
        String needAutoDownload = file.getExt9();
        String statParams = file.getExt10();

        ParamsWrapper pw = new ParamsWrapper();
        pw.setKey(key);
        pw.setResUrl(resUrl);
        pw.setFilePath(savePath);
        pw.setFileName(fileName);
        pw.setFileSize(fileSize);
        pw.setClassId(classId);
        pw.setExt1(iconUrl);
        pw.setExt2(packageName);
        pw.setExt3(versionCode);
        pw.setExt4(versionName);
        pw.setExt5(appId);
        pw.setExt6(gameid);
        pw.setExt7(downloadSourceId);
        pw.setExt8(downloadCompleteTime);
        pw.setExt9(needAutoDownload);
        pw.setExt10(statParams);

        return pw;
    }

    /**
     * 查询是否下载完毕
     * 
     * @param key
     * @return
     */
    public static boolean isDownloadFinish(String key) {
        DownloadFile file = DownloadOperator.getInstance().query(key);
        if (file != null) {
            int state = file.getState();
            if (state == FileDownloader.FINISH) {
                return FileUtil.isFileExist(file.getFilePath());
            }
        }

        return false;
    }

    /**
     * 快速查询是否下载完毕
     * 
     * @param key
     * @return
     */
    public static boolean isDownloadFinishFast(String key) {
        if (sDownloadStateTable.containsKey(key)) {
            return sDownloadStateTable.get(key);
        } else {
            return false;
        }
    }

    /**
     * 删除下载任务
     * 
     * @param downloadFile
     * @param realDelete 是否真的删除，true时将会把数据库条目与对应的临时文件删除
     */
    public static void cancelDownload(DownloadFile downloadFile, boolean realDelete) {
        DownloadServiceUtil.cancelDownload(downloadFile, realDelete);
    }

    /**
     * 设置应用在缓存和本地数据库中的自动下载标记
     * 
     * @param filehash 应用对应的filehash
     * @param autoNeedAutoDownload 是否需要自动下载 1需要，0不需要
     */
    public static void setAppAutoDownloadFlag(String filehash, int autoNeedAutoDownload) {
        DownloadFile file = DownloadServiceUtil.getDownloadFileFromCache(filehash);
        if (file != null) {
            file.setExt9(String.valueOf(autoNeedAutoDownload));
            DownloadOperator.getInstance().update(file, filehash);
        }

    }

}
